package com.example.interceptor;

import com.example.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wgw1206798585@vip.qq.com
 * @version 1.0
 * @date 2020-03-14 10:24
 *//*
 * 进入controller层之前拦截请求
 * 返回值：表示是否将当前的请求拦截下来  false：拦截请求，请求别终止。true：请求不被拦截，继续执行
 * Object obj:表示被拦的请求的目标对象（controller中方法）
 */
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("现在执行了preHandle方法");
        System.out.println(handler);//看上面注释
        User user = (User) request.getSession().getAttribute("session_user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user/toIndex");//拦截后跳转的方法
            System.out.println("已经成功拦截并进行了重定向");
            return false;
        }
        System.out.println("请求合格，放行！");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("现在执行了postHandle方法");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("现在执行了afterCompletion方法");

    }
}
